package com.joyxy.examples;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joyxy.core.ImageMatcher;
import com.joyxy.core.RobotController;
import com.joyxy.core.ScreenCapture;

/**
 * 简单游戏机器人示例
 * 演示基本的自动化操作
 */
public class SimpleGameBot {
    private static final Logger logger = LoggerFactory.getLogger(SimpleGameBot.class);
    
    private final RobotController robot;
    private final ScreenCapture screenCapture;
    private final ImageMatcher imageMatcher;
    
    public SimpleGameBot() throws AWTException {
        this.robot = new RobotController();
        this.screenCapture = new ScreenCapture();
        this.imageMatcher = new ImageMatcher();
        
        logger.info("简单游戏机器人初始化完成");
    }
    
    /**
     * 示例：点击游戏中的按钮
     */
    public void clickGameButton(String buttonTemplate) {
        logger.info("查找并点击按钮: {}", buttonTemplate);
        
        // 截取当前屏幕
        BufferedImage screenshot = screenCapture.captureFullScreen();
        if (screenshot == null) {
            logger.error("截图失败");
            return;
        }
        
        // 查找按钮位置
        Point buttonLocation = imageMatcher.findImage(screenshot, buttonTemplate);
        if (buttonLocation != null) {
            logger.info("找到按钮位置: ({}, {})", buttonLocation.x, buttonLocation.y);
            robot.click(buttonLocation.x, buttonLocation.y);
            robot.delay(1000); // 等待响应
        } else {
            logger.warn("未找到按钮: {}", buttonTemplate);
        }
    }
    
    /**
     * 示例：连续点击操作
     */
    public void performClickSequence() {
        logger.info("执行连续点击序列");
        
        // 点击开始按钮
        clickGameButton("templates/start_button.png");
        
        // 等待游戏加载
        robot.delay(3000);
        
        // 点击继续按钮
        clickGameButton("templates/continue_button.png");
        
        // 等待进入游戏
        robot.delay(2000);
    }
    
    /**
     * 示例：键盘操作
     */
    public void performKeyboardActions() {
        logger.info("执行键盘操作");
        
        // 按方向键移动
        robot.keyPress(KeyEvent.VK_W); // 向前
        robot.delay(500);
        
        robot.keyPress(KeyEvent.VK_A); // 向左
        robot.delay(500);
        
        robot.keyPress(KeyEvent.VK_S); // 向后
        robot.delay(500);
        
        robot.keyPress(KeyEvent.VK_D); // 向右
        robot.delay(500);
        
        // 按空格键跳跃
        robot.keyPress(KeyEvent.VK_SPACE);
        robot.delay(1000);
    }
    
    /**
     * 示例：鼠标拖拽操作
     */
    public void performDragAction() {
        logger.info("执行拖拽操作");
        
        // 从屏幕中心拖拽到右下角
        Dimension screenSize = screenCapture.getScreenSize();
        int centerX = screenSize.width / 2;
        int centerY = screenSize.height / 2;
        int targetX = (int) (screenSize.width * 0.8);
        int targetY = (int) (screenSize.height * 0.8);
        
        robot.drag(centerX, centerY, targetX, targetY);
        robot.delay(1000);
    }
    
    /**
     * 示例：检查游戏状态
     */
    public boolean checkGameState(String stateTemplate) {
        logger.debug("检查游戏状态: {}", stateTemplate);
        
        BufferedImage screenshot = screenCapture.captureFullScreen();
        if (screenshot == null) {
            return false;
        }
        
        Point stateLocation = imageMatcher.findImage(screenshot, stateTemplate);
        boolean stateFound = stateLocation != null;
        
        if (stateFound) {
            logger.info("检测到游戏状态: {}", stateTemplate);
        }
        
        return stateFound;
    }
    
    /**
     * 示例：等待特定界面出现
     */
    public boolean waitForScreen(String screenTemplate, int timeoutSeconds) {
        logger.info("等待界面出现: {}, 超时: {}秒", screenTemplate, timeoutSeconds);
        
        long startTime = System.currentTimeMillis();
        long timeout = timeoutSeconds * 1000L;
        
        while (System.currentTimeMillis() - startTime < timeout) {
            if (checkGameState(screenTemplate)) {
                logger.info("界面已出现: {}", screenTemplate);
                return true;
            }
            
            robot.delay(500); // 每500ms检查一次
        }
        
        logger.warn("等待界面超时: {}", screenTemplate);
        return false;
    }
    
    /**
     * 示例：完整的游戏自动化流程
     */
    public void runGameAutomation() {
        logger.info("开始游戏自动化流程");
        
        try {
            // 1. 等待游戏主菜单
            if (!waitForScreen("templates/main_menu.png", 30)) {
                logger.error("未检测到游戏主菜单，退出");
                return;
            }
            
            // 2. 点击开始游戏
            clickGameButton("templates/start_game_button.png");
            
            // 3. 等待游戏加载完成
            if (!waitForScreen("templates/game_loaded.png", 60)) {
                logger.error("游戏加载超时，退出");
                return;
            }
            
            // 4. 执行游戏操作
            for (int i = 0; i < 10; i++) {
                logger.info("执行游戏循环 {}/10", i + 1);
                
                // 检查是否需要点击继续
                if (checkGameState("templates/continue_dialog.png")) {
                    clickGameButton("templates/ok_button.png");
                }
                
                // 执行一些基本操作
                performKeyboardActions();
                
                // 检查胜利条件
                if (checkGameState("templates/victory_screen.png")) {
                    logger.info("检测到胜利界面，游戏完成");
                    break;
                }
                
                // 检查失败条件
                if (checkGameState("templates/game_over.png")) {
                    logger.info("检测到游戏结束，重新开始");
                    clickGameButton("templates/restart_button.png");
                    robot.delay(3000);
                }
                
                robot.delay(2000); // 等待2秒后继续
            }
            
            logger.info("游戏自动化流程完成");
            
        } catch (Exception e) {
            logger.error("游戏自动化过程中发生错误", e);
        }
    }
    
    /**
     * 示例程序入口
     */
    public static void main(String[] args) {
        try {
            SimpleGameBot bot = new SimpleGameBot();
            
            // 可以根据命令行参数执行不同的操作
            if (args.length > 0) {
                String action = args[0];
                switch (action) {
                    case "click":
                        if (args.length > 1) {
                            bot.clickGameButton(args[1]);
                        }
                        break;
                    case "keyboard":
                        bot.performKeyboardActions();
                        break;
                    case "drag":
                        bot.performDragAction();
                        break;
                    case "auto":
                        bot.runGameAutomation();
                        break;
                    default:
                        logger.info("未知操作: {}", action);
                        break;
                }
            } else {
                // 默认运行完整自动化流程
                bot.runGameAutomation();
            }
            
        } catch (Exception e) {
            logger.error("程序执行失败", e);
        }
    }
} 